Conditional Execution

Boolean Expressions

We introduce a new value type, the boolean. A boolean can have one of two values: True or False


In [ ]:
cleaned_room = True
took_out_trash = False

print(cleaned_room)
print(type(took_out_trash))

Comparison Operators

You can compare values together and get a boolean result

Operator Meaning
x == y x equal to y
x != y x not equal to y
x > y x greater than y
x < y x less than y
x >= y x greater than or equal to y
x <= y x less than or equal to y
x is y x is the same as y
x is not y x is not the same as y

By using the operators in an expression the result evaluates to a boolean. x and y can be any type of value


In [ ]:
print(5 == 6)

In [ ]:
print("Coke" != "Pepsi")

In [ ]:
# You can compare to variables too
allowance = 5

print(5 >= allowance)

In [ ]:
print(allowance is True)

TRY IT

See if 5.0000001 is greater than 5


In [ ]:

Conditional Execution

We can write programs that change their behavior depending on the conditions.

We use an if statement to run a block of code if a condition is true. It won't run if the condition is false.

if (condition):
    code_to_execute # if condition is true

In python indentation matters. The code to execute must be indented (4 spaces is best, though I like tabs) more than the if condition.


In [ ]:
# cleaned_room is true
if cleaned_room:
    print("Good kid! You can watch TV.")
    
# took_out_trash if false
if took_out_trash:
    print("Thank you!")
    
print(took_out_trash)

You can include more than one statement in the block of code in the if statement. You can tell python that this code should be part of the if statement by indenting it. This is called a 'block' of code

if (condition):
    statement1
    statement2
    statement3

You can tell python that the statement is not part of the if block by dedenting it to the original level

if (condition):
    statement1
    statement2
statement3 # statement3 will run even if condition is false

In [ ]:
# cleaned_room is true
if cleaned_room:
    print("Good job! You can watch TV.")
    print("Or play outside")

In [ ]:
# took_out_trash is false
if took_out_trash:
    print("Thank you!")
    print("You are a good helper")
print("It is time for lunch")

In alternative execution, there are two possibilities. One that happens if the condition is true, and one that happens if it is false. It is not possible to have both execute.

You use if/else syntax

if (condition):
    code_runs_if_true
else:
    code_runs_if_false

Again, note the colons and spacing. These are necessary in python.


In [ ]:
candies_taken = 4

if candies_taken < 3:
    print('Enjoy!')
else:
    print('Put some back')

Chained conditionals allow you to check several conditions. Only one block of code will ever run, though.

To run a chained conditional, you use if/elif/else syntax. You can use as many elifs as you want.

if (condition1):
    run_this_code1
elif (condition2):
    run_this_code2
elif (condition3):
    run_this_code3
else:
    run_this_code4

You are not required to have an else block.

if (condition1):
    run_this_code1
elif (condition2):
    run_this_code2

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.


In [ ]:
did_homework = True
took_out_trash = True
cleaned_room = False
allowance = 0
if cleaned_room:
    allowance = 10
elif took_out_trash:
    allowance = 5
elif did_homework:
    allowance = 4
else:
    allowance = 2
print(allowance)

TRY IT

Check if did_homework is true, if so, print out "You can play a video game", otherwise print out "Go get your backpack"


In [ ]:

Logical Operators

Logical operators allow you to combine two or more booleans. They are and, or, not

and Truth table (only true if both values are true)

val1 val2 val1 and val2
true true true
true false false
false true false
false false false

or Truth table (true if at least 1 value is true)

val1 val2 val1 or val2
true true true
true false true
false true true
false false false

not Truth table (the opposite of the value)

val1 not val1
true false
false true

In [ ]:
print(True and True)
      
print(False or True)

print(not False)

You can use the logical operators in if statements


In [ ]:
cleaned_room = True
took_out_trash = False
if cleaned_room and took_out_trash:
    print("Let's go to Chuck-E-Cheese's.")
else:
    print("Get to work!")

In [ ]:
if not did_homework:
    print("You're going to get a bad grade.")

TRY IT

Check if the room is clean or the trash is taken out and if so print "Here is your allowance"


In [ ]:

Nested Conditionals

You can nest conditional branches inside another. You just indent each level more.

if (condition):
    run_this
else:
    if (condition2):
       run_this2
    else:
       run_this3

Avoid nesting too deep, it becomes difficult to read.


In [ ]:
allowance = 5

if allowance > 2:
    if allowance >= 8:
        print("Buy toys!")
    else:
        print("Buy candy!")
else:
    print("Save it until I have enough to buy something good.")

Catching exceptions using try and except

You can put code into a try/except block. If the code has an error in the try block, it will stop running and go to the except block. If there is no error, the try block completes and the except block never runs.

try:
    code
except:
    code_runs_if_error

In [ ]:
try:
    print("Before")
    y = 5/0
    print("After")
except:
    print("I'm sorry, the universe doesn't work that way...")

A finally statment can be added to the try/except block and it executes at the end whether or not there is an error. This can be useful for cleaning up resources.

try:
    code
except:
    code_runs_if_error
finally:
    code runs at end with or without error

In [ ]:
try:
    print("Before")
    y = 5/0
    print("After")
except:
    print("I'm sorry, the universe doesn't work that way...")
finally:
    print("Even if you break python, you still have to do your chores")

This can be useful when evaluating a user's input, to make sure it is what you expected.


In [ ]:
inp = input('Enter Fahrenheit Temperature:')
try:
    fahr = float(inp)
    cel = (fahr - 32.0) * 5.0 / 9.0
    print(cel)
except:
    print('Please enter a number')

TRY IT

Try converting the string 'candy' into an integer. If there is an error, print "What did you think would happen?"


In [ ]:

Short-circuit evaluation of logical expressions

Python (and most other languages) are very lazy about logical expressions. As soon as it knows the value of the whole expression, it stops evaluating the expression.

if (condition1 and condition2):
    run_code

In the above example, if condition1 is false then condition2 is never evaluated.


In [ ]:
if (1 < 2) or (5/0):
    print("How did we do that?")

PROJECT: Car selector

We are going to build an application that recommends a car based on the user's budget.

  1. Ask the user what their car buying budget is and store in a variable called budget.
  2. Try to convert the budget into an integer and store back in the variable called budget.
  3. If step 2 fails print out "Please be realistic, you can't buy a car on rainbows and love."
  4. If their budget is greater than 75000, tell them to buy a Tesla.
  5. If their budget is less than 500 tell them they are better off riding the bus (it will be more reliable than a $500 car)
  6. Otherwise, tell them to buy a Toyota Corolla or something.
  7. Regardless of what their budget is let them know they can get all their car shopping done at "[your name here] Auto Depot."

In [ ]: